/**
 * 用法等同于 Grid
 * 
 <style>
		.x-grid3-row-over .x-grid3-cell-inner {   
 		 color:'#545BED'  
		}  
</style>
 
 
  var oIndexGrid = new Ext.ux.grid.CustomerGrid({
	 id:'id_oIndexGrid',
     key:'key_gridInfo',
	 height:all_height,
	 isBbarSpecial:false,
	 baseParams:{},
	 pageSize:20,
	 title:'',
 	 isPage:true,
 	 listeners:{
 	  'afterRender':function(){
 	    Ext.getCmp('id_oIndexGrid').setWidth(all_width - 232);
 	    var divs = document.getElementsByTagName('img');
 	    for(var i=0;i<divs.length;i++){
 	      if(divs[i].className =='x-panel-inline-icon icon-grid'&&null!=divs[i].nextSibling&&divs[i].nextSibling.innerHTML==''){
 	           divs[i].parentNode.parentNode.removeChild(divs[i].parentNode);
 	      }
 	    }
 	    
 	 
     }
 	 },
 	 
	 groupColumn:'户号',
	 columnNames:['户号','享受资格人数','详细地址','主房面积','附房面积','享受面积数','应置换面积','有效还迁面积','协议安置面积','户口人数']
	 ,callback:function(cm){
			cm.setRenderer(cm.findColumnIndex('户号'),function(value,p,record){
				return "<a style='TEXT-DECORATION:none' href='#' onclick='dispalyForm(\""+value+"\")'>"+value+"</a>";
			});
			cm.setColumnWidth(cm.findColumnIndex('身份证号码'),150);
			
	 }             
	});
 
 
 
 
 
 
 */

Ext.ns('Ext.ux.grid');
Ext.ux.grid.CustomerGrid = Ext.extend(Ext.grid.EditorGridPanel, {

	initComponent : function() {
		Grid.superclass.initComponent.call(this);
		this.pageSize = this.pageSize || 20;
		this.baseParams = this.baseParams || {};
		this.baseParams.key = this.key;
		this.tools = this.tools || [];
		me = this;
		if (!isNull(this.isRemoteExport)) {
			this.tools.push({
				id : 'save',
				qtip : '导出Excel',
				handler : function(e, t, p) {
					p.exportData(p.isRemoteExport);
				}
			});
		}
		this.viewConfig = {
			columnsText : '显示列',
			sortAscText : '升序',
			sortDescText : '降序',
			forceFit : this.isForceFit
		};
		if (this.isCheck && isNull(this.singleSelect)) {
			this.singleSelect = false;
		}
		if (this.isCheck && isNull(this.checkOnly)) {
			this.checkOnly = false;
		}
		this.selModel = this.isCheck ? new Ext.grid.CheckboxSelectionModel({
			gridId : this.id,
			singleSelect : this.singleSelect,
			checkOnly : this.checkOnly
		}) : null;
		if (!isNull(this.checkId)) { // 多选自动保存编号,需要配置checkId
			this.selModel.on("rowselect", function(o, index, record) { // 保存选中行,翻页保存用
						var grid = Ext.getCmp(o.gridId);
						var flag = false;
						for (var i = 0; i < grid.checkedRecord.length; i++) {
							if (grid.checkedRecord[i][grid.checkId] == record.data[grid.checkId]) {
								flag = true;
								break;
							}
						}
						if (!flag) {
							grid.checkedRecord.push(record.data);
						}
					});
			this.selModel.on("rowdeselect", function(o, index, record) { // 删除选中行,翻页保存用
						var grid = Ext.getCmp(o.gridId);
						for (var i = 0; i < grid.checkedRecord.length; i++) {
							if (grid.checkedRecord[i][grid.checkId] == record.data[grid.checkId]) {
								grid.checkedRecord.splice(i, 1);
								return;
							}
						}

					});
		}
		if (isNull(this.height)) {
			this.autoHeight = true;
		}
		if (!this.url) {
			if (this.isCommonAdapter) {
				this.baseParams.adapter_id_ = this.adapter_id_;
				this.url = '/customerDetailQueryController.table';
			} else {
				this.url = '/adapter2Table.table';
			}
		}
		if (this.autoLoad == null) {
			this.autoLoad = {
				params : {
					start : 0,
					limit : this.pageSize
				}
			};
		}
		var url_ = this.url
				+ (this.url.indexOf("?") > -1 ? "&decorate=no" : "?decorate=no");
		var storeParam = {
			id : this.id + '-ds',
			gridId : this.id,
			url : getRootPath() + url_,
			remoteSort : this.isRemoteSort,
			baseParams : this.baseParams,
			form : this.form,
			autoLoad : this.autoLoad,
			head : '',
			reader : new Ext.data.JsonReader({
				root : 'data',
				totalProperty : 'totalCount'
			}),
			sortInfo : ((!isNull(this.groupField)) && isNull(this.sortInfo))
					? {
						field : this.groupField,
						direction : "ASC"
					}
					: this.sortInfo,
			groupField : this.groupField
		};
		var ds;
		if (isNull(this.groupField)) {
			ds = new Ext.data.Store(storeParam);
		} else {
			ds = new Ext.data.GroupingStore(storeParam);
			this.view = new Ext.grid.GroupingView({
				forceFit : true,
				groupTextTpl : '{text} ({[values.rs.length]} 条记录)'
			});
		}
		this.store = ds;
		if (this.isPage) {
			 var Message='显示 {0} - {1} 条记录,共 {2}条';
			if (this.showShort == true) {
				Message = '';
			}

			this.bbar = new Ext.PagingToolbar({
				height : 30,
				id : 'id_msgBar',
				afterPageText : '/ {0}',
				beforePageText : '页',
				firstText : '第一页',
				prevText : '前一页',
				nextText : '后一页',
				lastText : '最后一页',
				refreshText : '刷新',
				store : this.store,
				pageSize : this.pageSize,
				displayInfo : true,
				displayMsg : Message,
				emptyMsg : "没有数据",
				items:[{xtype:'label',style:'paddingLeft:200',html:'<div id="id_div_bbarInfo"></div>'}]
				});
			if (this.bbar) {
				this.elements += ',bbar';
				if (typeof this.bbar == 'object') {
					this.bottomToolbar = this.bbar;
				}
				delete this.bbar;
			}
		}
		this.ds = ds;
		ds.on("beforeload", function(o, options) {
			if (!isNull(this.form)) {
				var params = this.form.getForm().getValues();
				function eachItem(item, index, length) {
					if (item.isXType("xlovcombo")) {
						if (item.getValue() != null
								&& item.getValue().trim() != "''") {
							params[item.id] = item.getValue();
						} else {
							params[item.id] = null;
						}
					}
				}
				this.form.items.each(eachItem);
				Ext.apply(this.baseParams, params);
				Ext.apply(options.params, params);
			}
		});
		// 可多选时能自动选中，为了翻页
		if (!isNull(this.checkId)) { // 多选自动保存编号,需要配置checkId
			this.store.on('load', function(store, records, options) {
				var grid = Ext.getCmp(store.gridId);
				var index = [];
				for (var i = 0; i < records.length; i++) {
					for (var j = 0; j < grid.checkedRecord.length; j++) {
						if (records[i].data[grid.checkId] == grid.checkedRecord[j][grid.checkId]) {
							index.push(i);
							break;
						}
					}
				}
				grid.getSelectionModel().selectRows(index, true);
			});
		}
		ds.on("preload", function(a, b) {
			reconfig(a, b, this.gridId)
		});
		if (this.isLock) {
			this.colModel = new Ext.ux.grid.LockingColumnModel([{}]);
			this.view = new Ext.ux.grid.LockingGridView();
		} else {
			this.colModel = new Ext.grid.ColumnModel([{}]);
		}
		this.colModel.defaultSortable = (this.isRemoteSort != null || false);
		// this.selModel=new Ext.grid.RowSelectionModel();
		if (this.selColumn) {// 判断是否有自定义列功能，设为true时页面需要引入webContent/ext3.1/js/gridAdvanced.js
			this.tools.push({
				id : 'gear',
				qtip : '自定义列',
				handler : function(e, target, grid) {

					if (Ext.getCmp('selColumn_win_' + grid.id) == undefined) {
						selColumn(grid.key, grid.id, grid.adapter_id_);
					}
					var root = Ext.getCmp('selColumn_tree_panel_' + grid.id).root;
					root.expand();
					if (!root.firstChild) {
						root.appendChild(grid.getTree());
					}
					Ext.getCmp('selColumn_win_' + grid.id).show();
				}
			});
		}
		if (this.selQuery) {// 判断是否有自定义查询功能，设为true时页面需要引入webContent/ext3.1/js/gridAdvanced.js
			this.tools.push({
				id : 'pin',
				qtip : '高级查询',
				handler : function(e, target, grid) {
					if (Ext.getCmp('selQuery_win_' + grid.id) == undefined) {
						selQuery(grid.key, grid.id, grid.adapter_id_);
						Ext.getCmp('selQuery_tree_panel_' + grid.id).root
								.expand();
						Ext.getCmp('selQuery_tree_panel_' + grid.id).root
								.appendChild(grid.getTree());
					}
					Ext.getCmp('selQuery_win_' + grid.id).show();
					Ext.getCmp('gridSelQuery_' + grid.id).load();
				}
			});
		}
		this.checkedRecord = this.checkedRecord || [];
		// 跨多行
		if (this.columnNames) {
			this.cls = 'rowspan-style';
			this.view = new Ext.ux.grid.CustomerGridView({
				columnNames : this.columnNames,
				groupColumn : this.groupColumn,
				forceFit : this.isForceFit
			});
		}
		
		
	},

	/**
	 * 初始化属性并赋默认值
	 */
	customercolumn : '_customer_column_',
	bodyStyle : 'padding:0px',
	clicksToEdit : 1,
	stripeRows : true,
	trackMouseOver : true,
	iconCls : 'icon-grid',
	loadMask : {
		msg : '正在加载数据，请稍候……'
	},
	cm : null,
	enableColumnMove : false,
	enableHdMenu : false,

	/**
	 * 方法
	 */
	setKey : function(key) {
		this.ds.baseParams.key = key;
	},
	getKey : function() {
		return this.ds.baseParams.key;
	},
	setCallBack : function(callback) {
		this.ds.callback = callback;
	},
	load : function() {
		this.ds.load({
			params : {
				start : 0,
				limit : this.pageSize
			}
		});
	},
	reload : function() {
		this.store.load();
	},
	getParam : function(p) {
		return this.ds.baseParams[p];
	},
	setParam : function(p, v) {
		this.ds.baseParams[p] = v;
	},
	setParams : function(j) {
		for (var p in j) {
			this.setParam(p, j[p]);
		}
	},
	getHead : function() {
		return this.ds.head;
	},
	exportData : function(flag) {
	
		if (flag) {
			 if(this.title=='')
			 {
			  this.title ='新文件';
			 }
		
			var url = getRootPath() + "/extExportExcel.report?decorate=no&key="
					+ this.ds.baseParams.key + "&filename="
					+ encodeURI(this.title);
			for (var p in this.ds.baseParams) {
				url += "&" + p + "=" + this.ds.baseParams[p];
			}
			url += "&isExcelRank=" + this.isExcelRank;
			if (this.isCommonAdapter) {
				var start = 0, limit = this.ds.getTotalCount();
				url += "&adapter_id_=" + this.adapter_id_ + "&start=" + start
						+ "&limit=" + limit;
			}
			if(this.columnNames){
				url+='&columnNames='+this.columnNames+"&groupColumn="+this.groupColumn;
		     }
			window.location.href = url;
		} else {
			exportData(this.id, this.title);
		}
	},
	getTree : function() {
		var j1 = this.ds.head;
		var j2 = "[{}";
		for (var p = 0; p < j1.length; p++) {
			if (j1[p].dataIndex.indexOf(this.customercolumn) == -1)
				j2 += ",{'text':'" + j1[p].header
						+ "',expanded: false,leaf:true}";
		};
		j2 += "]";
		j2 = eval(j2.replace("{},", ""));
		return j2;
	},
	getSelectionsByCheckId : function() {
		var result = '';
		for (var i = 0; i < this.checkedRecord.length; i++) {
			result += "'" + this.checkedRecord[i][this.checkId] + "'";
			if (i + 1 < this.checkedRecord.length)
				result += ',';
		}
		return result;
	},
	getSelections : function(target) {
		var rows = this.getSelectionModel().getSelections();
		if (rows == '')
			return null;
		var result = '';
		for (var i = 0; i < rows.length; i++) {
			result += rows[i].get(target);
			if (i + 1 < rows.length)
				result += ',';
		}
		return result;
	},
   setBbarMsg:function(start,end,totalPeople,totalHouse){
  	 var divs =    document.getElementsByTagName('div');
          for (var index = 0; index < divs.length; index++) {
          	  if(divs[index].className =='xtb-text'&&divs[index].innerHTML=='##jack##Bbar##special'){
          	     divs[index].innerHTML ='显示 '+start+'-'+end+'户 其中村民 '+totalPeople+'人共'+totalHouse+'户&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;';
          	  }
          }
   }
});

Ext.reg('cGrid', Ext.ux.grid.CustomerGrid);
// 自动获取表头,并重新配置到reader
function reconfig(o, j, gridId) {
 
	var s = Ext.getCmp(gridId);
	var fullExpand = '';
	var data;
	var sort = '';
	var j_;
	var flag = true; // 是否回调的标志
	try {
		data = eval("(" + j + ")");
		j_ = data.data[0];
	} catch (e) {
		alert("json格式错误,解析失败!");
	}
	var head = "[{}";
	var edit = '';
	if (data && data.norecord) {
		// 没数据
		flag = false;
	} else if (data && data.error) {
		// 错误信息
		flag = false;
		show_error_message_win(data.error);
	} else {
		if (s.isRemoteSort != null)
			sort = ",\"sortable\":true";
		if (s.isRank)
			head += ",new Ext.grid.RowNumberer()";
		if (s.isCheck)
			head += ",new Ext.grid.CheckboxSelectionModel()";
		edit = s.isEdit == true
				? ',editor: new Ext.form.TextField({allowBlank: true})'
				: '';
	}
	var reader = "[{}"
	for (var p in j_) {
		if (p && trim(p) != '' && p != 'ordertype' && p != 'recordnum') {
			var lock = '';
			if (s.lockedField && s.lockedField.indexOf(p) != -1)
				lock = ',locked: true';
			head += ",{\"header\":\"" + p.replace(s.customercolumn, '')
					+ "\",\"dataIndex\":\"" + p + "\"" + edit + fullExpand
					+ sort + lock + "}";
			reader += ",{\"name\":\"" + p + "\"}";
		}
	}
	head += "]";
	reader += "]";
	head = eval(head.replace("{},", ""));
	reader = eval(reader.replace("{},", ""));
	s.ds.head = head;
	s.getColumnModel().setConfig(head);
	o.reader = new Ext.data.JsonReader({
		root : 'data',
		totalProperty : 'totalCount'
	}, reader);
	o.recordType = o.reader.recordType;
	s.ds.fields = o.recordType.prototype.fields;
	var cm = s.getColumnModel();
	cm.setEditor = function(i, c) {
		cm.config[i].editor.destroy();
		cm.config[i].editor = new Ext.grid.GridEditor(c);
	};
	if (flag && s.callback)
		s.callback(cm);
}
// 非空判断
function isNull(o) {
	return (typeof(o) == 'undefined' || o == null);
}